package com.bumptech.glide.load.data;

import ohos.app.Context;
import ohos.utils.net.Uri;
import com.bumptech.glide.util.LogUtil;
import org.jetbrains.annotations.NotNull;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import java.io.FileNotFoundException;
import java.io.IOException;

public abstract class VideoLocalUriFetcher<T> implements DataFetcher<T>{

    private static final String TAG = "VideoLocalUriFetcher";
    private final Uri uri;
    private final Context context;
    private T data;

    //Public API.
    //WeakerAccess
    public VideoLocalUriFetcher(Context context, Uri uri){

        this.context = context;
        this.uri =uri;
    }

    @Override
    public void loadData(@NotNull Priority priority,@NotNull DataCallback<? super T> callback) {

        try{
            data = loadResource(uri, context);
            callback.onDataReady( data);
        }catch (FileNotFoundException e){
            if(LogUtil.isLoggable(TAG, LogUtil.DEBUG)){
                LogUtil.debug(TAG, "Failed to open uri" + e);
            }
            callback.onLoadFailed( e);
        }
    }

    @Override
    public void cleanup() {
        if (data != null){
            try{
                close( data);
            }
            catch (IOException e){
                //Ignored
            }
        }
    }

    @Override
    public void cancel() {
        //Do nothing
    }


    @Override
    public DataSource getDataSource() {
        return DataSource.LOCAL;
    }

    protected abstract T loadResource(Uri uri, Context context)
        throws FileNotFoundException;

    protected abstract void close(T data) throws IOException;
}
